package com.elitetyc.elitetyc_plugin;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.view.KeyEvent;
import android.widget.TextView;
import androidx.annotation.NonNull;
import com.alibaba.fastjson.JSONObject;
import com.demo.scan.MainActivity;
import com.taobao.weex.WXSDKInstance;
import com.taobao.weex.ui.action.BasicComponentData;

import com.taobao.weex.ui.component.WXComponent;
import com.taobao.weex.ui.component.WXVContainer;

import java.util.HashMap;
import java.util.Map;

/**
 * 监听PDA 按键
 */
public class KeyReceiverComponent extends WXComponent<TextView> {

    private KeyReceiver keyReceiver;
    /**
     * 按键广播接收者 用于接受按键广播 触发扫描
     */
    private boolean mIsPressed = false;

    public KeyReceiverComponent(WXSDKInstance instance, WXVContainer parent, BasicComponentData basicComponentData) {
        super(instance, parent, basicComponentData);
        //注册按键广播接收者
        keyReceiver = new KeyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.rfid.FUN_KEY");
        filter.addAction("android.intent.action.FUN_KEY");
        this.getContext().registerReceiver(keyReceiver , filter);
    }
    /**
     *构建component的view时会回调此函数
     * @param context
     * @return
     */
    @Override
    protected TextView initComponentHostView(@NonNull Context context) {
        TextView textView = new TextView(context);
        textView.setTextColor(Color.RED);
        textView.setTextSize(30);
        return textView;
    }

    private class KeyReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int keyCode = intent.getIntExtra("keyCode", 0);
            // 为兼容早期版本机器
            if (keyCode == 0) {
                keyCode = intent.getIntExtra("keycode", 0);
            }
            boolean keyDown = intent.getBooleanExtra("keydown", false);
            if (keyDown && !mIsPressed) {
                Map<String, Object> params = new HashMap<>();
                JSONObject jsonObject = new JSONObject();
                // 根据需要在对应的按键的键值中开启扫描,
                switch (keyCode) {
                    case KeyEvent.KEYCODE_F1:

                    case KeyEvent.KEYCODE_F2:

                    case KeyEvent.KEYCODE_F3:

                    case KeyEvent.KEYCODE_F4:

                    case KeyEvent.KEYCODE_F5:

                    default:
                        //开启扫描
                        mIsPressed = true;
                        break;
                }
                params.put("detail", jsonObject);
                fireEvent("onTel", params);
            }else {
                mIsPressed = false;
            }
        }
    }


}
